package com.retailcloud.baseservice.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.retailcloud.baseservice.dao.TenantsDao;

import com.retailcloud.baseservice.entity.TenantsEntity;
import com.retailcloud.baseservice.service.TokenService;
import com.retailcloud.commonutils.constant.UserRedisKeyConstant;
import com.retailcloud.commonutils.constant.UserRoleEnum;
import com.retailcloud.commonutils.dto.TenantsDTO;
import com.retailcloud.commonutils.dto.UserDTO;
import com.retailcloud.commonutils.utils.HttpContextUtils;
import com.retailcloud.commonutils.utils.PageUtils;
import com.retailcloud.commonutils.utils.Query;
import com.retailcloud.commonutils.utils.RedisUtils;
import com.sitech.idworkstarter.IdWorkService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.retailcloud.baseservice.dao.UsersDao;
import com.retailcloud.baseservice.entity.UsersEntity;
import com.retailcloud.baseservice.service.UsersService;

import javax.annotation.Resource;


@Service("usersService")
public class UsersServiceImpl extends ServiceImpl<UsersDao, UsersEntity> implements UsersService {
    @Resource
    TenantsDao tenantsDao;
    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    IdWorkService idWorkService;
    @Resource
    TokenService tokenService;

    @Resource
    RedisUtils redisUtils;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UsersEntity> page = this.page(
                new Query<UsersEntity>().getPage(params),
                new QueryWrapper<UsersEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public UserDTO init(UsersEntity users) {
        UserDTO userDTO = new UserDTO();
        /**
         * 根据用户的账号和密码查询用户信息，如果没有就创建用户
         */
        QueryWrapper<UsersEntity> usersEntityQueryWrapper = new QueryWrapper<>();
        usersEntityQueryWrapper.eq("wechat_openid", users.getWechatOpenid());
        usersEntityQueryWrapper.last("limit 1");
        UsersEntity usersEntity = baseMapper.selectOne(usersEntityQueryWrapper);
        if (usersEntity != null) {
            BeanUtils.copyProperties(usersEntity, userDTO);
            // 查询企业信息
            if (StringUtils.isNotBlank(usersEntity.getTenantId())) {
                QueryWrapper<TenantsEntity> tenantsEntityQueryWrapper = new QueryWrapper<>();
                tenantsEntityQueryWrapper.eq("tenant_id", usersEntity.getTenantId());
                tenantsEntityQueryWrapper.last("limit 1");
                TenantsEntity tenantsEntity = tenantsDao.selectOne(tenantsEntityQueryWrapper);
                TenantsDTO tenantsDTO = new TenantsDTO();
                usersEntity.setPassword("");
                BeanUtils.copyProperties(tenantsEntity, tenantsDTO);
                userDTO.setTenants(tenantsDTO);
            }
        } else {
            // 新增用户信息
            usersEntity = new UsersEntity();
            usersEntity.setWechatOpenid(users.getWechatOpenid());
            // 设置其他必要的用户信息
            usersEntity.setUsername(users.getUsername());
            String hashedPassword = passwordEncoder.encode("123456");
            usersEntity.setRole(UserRoleEnum.普通用户);
            usersEntity.setPhone(users.getPhone());
            usersEntity.setWechatNickname(users.getWechatNickname());
            usersEntity.setWechatAvatar(users.getWechatAvatar());
            String id = idWorkService.getSEQByKey("id_seq");
            usersEntity.setUserId(id);
            //初始密码为123456
            usersEntity.setPassword(hashedPassword);
            // 其他字段根据实际情况设置
            baseMapper.insert(usersEntity);
            usersEntity.setPassword("");
            // 将新插入的用户信息复制到UserDTO
            BeanUtils.copyProperties(usersEntity, userDTO);
            // 如果有企业信息，也可以在这里设置
            if (StringUtils.isNotBlank(users.getTenantId())) {
                QueryWrapper<TenantsEntity> tenantsEntityQueryWrapper = new QueryWrapper<>();
                tenantsEntityQueryWrapper.eq("tenant_id", users.getTenantId());
                tenantsEntityQueryWrapper.last("limit 1");
                TenantsEntity tenantsEntity = tenantsDao.selectOne(tenantsEntityQueryWrapper);
                TenantsDTO tenantsDTO = new TenantsDTO();
                BeanUtils.copyProperties(tenantsEntity, tenantsDTO);
                userDTO.setTenants(tenantsDTO);
            }

        }
        //生成token并添加到缓存中
        String token = tokenService.generateToken(users.getWechatOpenid(), JSONObject.toJSONString(userDTO));
        userDTO.setToken(token);
        return userDTO;
    }

    @Override
    public void updateUserInfoById(UsersEntity users) {
        UpdateWrapper<UsersEntity> usersEntityUpdateWrapper = new UpdateWrapper<>();
        usersEntityUpdateWrapper.eq("user_id", users.getUserId());
        usersEntityUpdateWrapper.last("limit 1");
        baseMapper.update(users, usersEntityUpdateWrapper);

        //重新获取用户信息
        UsersEntity usersEntity = baseMapper.selectById(users.getUserId());

        UserDTO userDTO = new UserDTO();
        usersEntity.setPassword("");
        BeanUtils.copyProperties(usersEntity, userDTO);
        if (StringUtils.isNotBlank(users.getTenantId())) {
            QueryWrapper<TenantsEntity> tenantsEntityQueryWrapper = new QueryWrapper<>();
            tenantsEntityQueryWrapper.eq("tenant_id", users.getTenantId());
            tenantsEntityQueryWrapper.last("limit 1");
            TenantsEntity tenantsEntity = tenantsDao.selectOne(tenantsEntityQueryWrapper);
            TenantsDTO tenantsDTO = new TenantsDTO();
            BeanUtils.copyProperties(tenantsEntity, tenantsDTO);
            userDTO.setTenants(tenantsDTO);
        }
        //刷新缓存
        redisUtils.set(UserRedisKeyConstant.USER_TOKEN_USER_KEY + usersEntity.getWechatOpenid(), JSONObject.toJSONString(userDTO));

    }

    @Override
    public UserDTO getUserInfoById() {
        UserDTO userDTO = new UserDTO();
        String openId = HttpContextUtils.getHttpServletRequest().getHeader("X-User-Name");
        //刷新缓存
        String userInfoJson = redisUtils.get(UserRedisKeyConstant.USER_TOKEN_USER_KEY + openId);
        if (StringUtils.isNotBlank(userInfoJson)) {
            return JSONObject.parseObject(userInfoJson, UserDTO.class);
        } else {
            QueryWrapper<UsersEntity> usersEntityQueryWrapper = new QueryWrapper<>();
            usersEntityQueryWrapper.eq("wechat_openid", openId);
            usersEntityQueryWrapper.last("limit 1");
            UsersEntity usersEntity = baseMapper.selectOne(usersEntityQueryWrapper);
            usersEntity.setPassword("");
            BeanUtils.copyProperties(usersEntity, userDTO);
            // 如果有企业信息，也可以在这里设置
            if (StringUtils.isNotBlank(usersEntity.getTenantId())) {
                QueryWrapper<TenantsEntity> tenantsEntityQueryWrapper = new QueryWrapper<>();
                tenantsEntityQueryWrapper.eq("tenant_id", usersEntity.getTenantId());
                tenantsEntityQueryWrapper.last("limit 1");
                TenantsEntity tenantsEntity = tenantsDao.selectOne(tenantsEntityQueryWrapper);
                TenantsDTO tenantsDTO = new TenantsDTO();
                BeanUtils.copyProperties(tenantsEntity, tenantsDTO);
                userDTO.setTenants(tenantsDTO);
            }
        }
        //刷新缓存
        redisUtils.set(UserRedisKeyConstant.USER_TOKEN_USER_KEY + openId, JSONObject.toJSONString(userDTO));
        return userDTO;
    }

}
